<template>
  <div class="min-h-screen bg-gray-50 profile-container">
    <!-- 顶部导航栏 -->
    <header class="sticky top-0 z-50 bg-white shadow-md transition-all duration-300">
      <div class="container mx-auto px-4">
        <div class="flex items-center justify-between h-16 md:h-20">
          <!-- Logo -->
          <div class="flex items-center">
            <router-link to="/home" class="flex items-center">
              <i class="fas fa-book text-primary text-2xl md:text-3xl mr-2"></i>
              <span class="text-xl md:text-2xl font-bold text-primary" style="font-weight: 700;">书香阁</span>
            </router-link>
          </div>

          <!-- 主导航 - 桌面版 -->
          <nav class="hidden md:flex items-center space-x-8">
            <router-link to="/home" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">首页</router-link>
            <router-link to="/category" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">分类</router-link>
            <router-link to="/bestseller" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">畅销榜</router-link>
            <router-link to="/news" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">资讯</router-link>
          </nav>

          <!-- 搜索框 -->
          <div class="hidden md:flex items-center flex-1 max-w-md mx-8">
            <div class="relative w-full flex">
              <el-input
                v-model="searchKeyword"
                placeholder="请输入您喜欢的商品"
                class="search-input flex-1"
                @keyup.enter="handleSearch"
              >
                <template #prefix>
                  <i class="fas fa-search text-gray-400"></i>
                </template>
              </el-input>
              <button
                @click="handleSearch"
                class="search-button ml-2 px-4 py-2 text-white rounded-full transition-colors flex items-center justify-center"
              >
                <i class="fas fa-search"></i>
              </button>
            </div>
          </div>

          <!-- 用户工具栏 -->
          <div class="flex items-center space-x-4">
            <button class="relative p-2 text-gray-600 hover:text-primary transition-colors">
              <i class="fas fa-bell text-lg"></i>
              <span class="absolute top-1 right-1 w-2 h-2 bg-red-500 rounded-full"></span>
            </button>
            <button
              @click="goToCart"
              class="relative p-2 text-gray-600 hover:text-primary transition-colors"
            >
              <i class="fas fa-shopping-cart text-lg"></i>
              <span class="absolute -top-1 -right-1 bg-primary text-white text-xs rounded-full w-5 h-5 flex items-center justify-center cart-badge">{{ cartCount }}</span>
            </button>

            <!-- 用户下拉菜单 -->
            <el-dropdown @command="handleCommand">
              <span class="el-dropdown-link cursor-pointer flex items-center">
                <el-avatar :size="32" :src="getImageUrl(userStore.userInfo?.avatar)">
                  <i class="fas fa-user"></i>
                </el-avatar>
                <span class="hidden md:block ml-2 text-gray-600">{{ userStore.userInfo?.username }}</span>
                <i class="fas fa-chevron-down ml-1 text-gray-400"></i>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">个人资料</el-dropdown-item>
                  <el-dropdown-item command="orders">我的订单</el-dropdown-item>
                  <el-dropdown-item command="settings">设置</el-dropdown-item>
                  <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

            <!-- 移动端菜单按钮 -->
            <button @click="toggleMobileMenu" class="md:hidden p-2 text-gray-600 hover:text-primary transition-colors">
              <i class="fas fa-bars text-xl"></i>
            </button>
          </div>
        </div>

        <!-- 移动端搜索框 -->
        <div class="md:hidden pb-4">
          <div class="flex">
            <el-input
              v-model="searchKeyword"
              placeholder="请输入您喜欢的商品"
              class="search-input flex-1"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <i class="fas fa-search text-gray-400"></i>
              </template>
            </el-input>
            <button
              @click="handleSearch"
              class="search-button ml-2 px-4 py-2 text-white rounded-full transition-colors flex items-center justify-center"
            >
              <i class="fas fa-search"></i>
            </button>
          </div>
        </div>
      </div>

      <!-- 移动端导航菜单 -->
      <div v-show="showMobileMenu" class="md:hidden bg-white border-t border-gray-100 shadow-lg">
        <div class="container mx-auto px-4 py-3 space-y-3">
          <router-link to="/home" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">首页</router-link>
          <router-link to="/category" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">分类</router-link>
          <router-link to="/bestseller" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">畅销榜</router-link>
          <router-link to="/news" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">资讯</router-link>
        </div>
      </div>
    </header>

    <!-- 主要内容 -->
    <main class="container mx-auto px-4 py-6">
      <!-- 页面标题 -->
      <div class="mb-8">
        <h1 class="text-3xl font-bold text-gray-800 mb-2">个人资料</h1>
        <p class="text-gray-600">管理您的个人信息和账户设置</p>
      </div>

      <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <!-- 左侧菜单 -->
        <div class="lg:col-span-1">
          <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
            <div class="p-6 border-b border-gray-100">
              <div class="flex items-center">
                <el-avatar :size="64" :src="getImageUrl(userStore.userInfo?.avatar)" class="mr-4">
                  <i class="fas fa-user text-2xl"></i>
                </el-avatar>
                <div>
                  <h3 class="text-lg font-semibold text-gray-800">{{ userStore.userInfo?.username }}</h3>
                  <p class="text-gray-500 text-sm">{{ userStore.userInfo?.email }}</p>
                </div>
              </div>
            </div>
            <nav class="p-2">
              <button
                v-for="item in menuItems"
                :key="item.key"
                @click="activeTab = item.key"
                :class="[
                  'w-full text-left px-4 py-3 rounded-lg transition-colors flex items-center',
                  activeTab === item.key 
                    ? 'bg-primary/10 text-primary font-medium' 
                    : 'text-gray-600 hover:bg-gray-50 hover:text-primary'
                ]"
              >
                <i :class="item.icon" class="mr-3 text-lg"></i>
                {{ item.label }}
              </button>
            </nav>
          </div>
        </div>

        <!-- 右侧内容 -->
        <div class="lg:col-span-2">
          <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
            <!-- 基本信息 -->
            <div v-if="activeTab === 'basic'" class="space-y-6">
              <h2 class="text-xl font-semibold text-gray-800 mb-6">基本信息</h2>
              
              <el-form :model="profileForm" label-width="100px" class="space-y-4">
                <el-form-item label="用户名">
                  <el-input v-model="profileForm.username" placeholder="请输入用户名" />
                </el-form-item>
                
                <el-form-item label="邮箱">
                  <el-input v-model="profileForm.email" placeholder="请输入邮箱" />
                </el-form-item>
                
                <el-form-item label="手机号">
                  <el-input v-model="profileForm.phone" placeholder="请输入手机号" />
                </el-form-item>
                
                <el-form-item label="性别">
                  <el-radio-group v-model="profileForm.gender">
                    <el-radio :label="1">男</el-radio>
                    <el-radio :label="2">女</el-radio>
                    <el-radio :label="0">未设置</el-radio>
                  </el-radio-group>
                </el-form-item>
                
                <el-form-item label="生日">
                  <el-date-picker
                    v-model="profileForm.birthday"
                    type="date"
                    placeholder="选择日期"
                    style="width: 100%"
                  />
                </el-form-item>
                
                <el-form-item>
                  <el-button type="primary" @click="saveProfile">保存修改</el-button>
                  <el-button @click="resetProfile">重置</el-button>
                </el-form-item>
              </el-form>
            </div>

            <!-- 头像设置 -->
            <div v-if="activeTab === 'avatar'" class="space-y-6">
              <h2 class="text-xl font-semibold text-gray-800 mb-6">头像设置</h2>
              
              <div class="flex flex-col items-center space-y-4">
                <el-avatar :size="120" :src="getImageUrl(userStore.userInfo?.avatar)">
                  <i class="fas fa-user text-4xl"></i>
                </el-avatar>
                
                <div class="text-center">
                  <p class="text-gray-600 mb-4">支持 JPG、PNG 格式，文件大小不超过 2MB</p>
                  <el-button type="primary" @click="uploadAvatar">上传头像</el-button>
                </div>
              </div>
            </div>

            <!-- 安全设置 -->
            <div v-if="activeTab === 'security'" class="space-y-6">
              <h2 class="text-xl font-semibold text-gray-800 mb-6">安全设置</h2>

              <!-- 修改密码 -->
              <div class="bg-white p-6 rounded-lg border border-gray-200">
                <h3 class="text-lg font-medium text-gray-800 mb-6">修改密码</h3>

                <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px" class="max-w-md">
                  <el-form-item label="当前密码" prop="currentPassword" class="mb-6">
                    <el-input
                      v-model="passwordForm.currentPassword"
                      type="password"
                      placeholder="请输入当前密码"
                      show-password
                      size="large"
                      class="w-full"
                    />
                  </el-form-item>

                  <el-form-item label="新密码" prop="newPassword" class="mb-6">
                    <el-input
                      v-model="passwordForm.newPassword"
                      type="password"
                      placeholder="请输入新密码"
                      show-password
                      size="large"
                      class="w-full"
                    />
                  </el-form-item>

                  <el-form-item label="确认密码" prop="confirmPassword" class="mb-6">
                    <el-input
                      v-model="passwordForm.confirmPassword"
                      type="password"
                      placeholder="请再次输入新密码"
                      show-password
                      size="large"
                      class="w-full"
                    />
                  </el-form-item>

                  <el-form-item class="mb-0">
                    <div class="flex gap-3">
                      <el-button @click="resetPasswordForm" size="large">取消</el-button>
                      <el-button type="primary" @click="submitPasswordChange" :loading="passwordLoading" size="large">
                        <i class="fas fa-key mr-2"></i>修改密码
                      </el-button>
                    </div>
                  </el-form-item>
                </el-form>
              </div>
            </div>

            <!-- 地址管理 -->
            <div v-if="activeTab === 'address'" class="space-y-6">
              <div class="flex items-center justify-between">
                <h2 class="text-xl font-semibold text-gray-800">地址管理</h2>
                <el-button type="primary" @click="addAddress">添加新地址</el-button>
              </div>

              <div class="space-y-4">
                <div
                  v-for="address in addresses"
                  :key="address.id"
                  class="p-4 border border-gray-200 rounded-lg hover:shadow-md transition-all duration-300"
                >
                  <div class="flex items-start justify-between">
                    <div class="flex-1">
                      <div class="flex items-center mb-2 flex-wrap gap-2">
                        <span class="font-medium text-gray-800">{{ address.name }}</span>
                        <span class="text-gray-600">{{ address.phone }}</span>
                        <el-tag v-if="address.isDefault" type="primary" size="small">默认</el-tag>
                        <el-tag v-if="address.tag" :type="getTagType(address.tag)" size="small">
                          {{ getTagLabel(address.tag) }}
                        </el-tag>
                      </div>
                      <p class="text-gray-600 mb-2">{{ address.fullAddress }}</p>
                    </div>
                    <div class="flex space-x-2">
                      <el-button type="primary" plain size="small" @click="editAddress(address)">
                        <i class="fas fa-edit mr-1"></i>编辑
                      </el-button>
                      <el-button
                        type="danger"
                        plain
                        size="small"
                        @click="deleteAddress(address.id)"
                        :disabled="address.isDefault && addresses.length > 1"
                      >
                        <i class="fas fa-trash mr-1"></i>删除
                      </el-button>
                    </div>
                  </div>
                </div>

                <div v-if="addresses.length === 0" class="text-center py-12">
                  <div class="text-gray-400 mb-4">
                    <i class="fas fa-map-marker-alt text-6xl"></i>
                  </div>
                  <h3 class="text-lg font-medium text-gray-600 mb-2">暂无收货地址</h3>
                  <p class="text-gray-500 mb-4">添加收货地址，享受便捷的配送服务</p>
                  <el-button type="primary" @click="addAddress">
                    <i class="fas fa-plus mr-2"></i>
                    添加新地址
                  </el-button>
                </div>
              </div>
            </div>

            <!-- 我的收藏 -->
            <div v-if="activeTab === 'favorites'" class="space-y-6">
              <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                <h2 class="text-xl font-semibold text-gray-800">我的收藏</h2>

                <!-- 筛选和排序 -->
                <div class="flex flex-wrap items-center gap-3">
                  <el-select v-model="favoriteFilter" placeholder="筛选" style="width: 120px">
                    <el-option label="全部" value="all" />
                    <el-option label="有库存" value="inStock" />
                    <el-option label="缺货" value="outOfStock" />
                  </el-select>

                  <el-select v-model="favoriteSortBy" placeholder="排序" style="width: 120px">
                    <el-option label="收藏时间" value="time" />
                    <el-option label="价格" value="price" />
                    <el-option label="评分" value="rating" />
                  </el-select>

                  <el-button @click="clearAllFavorites" type="danger" plain size="small">
                    <i class="fas fa-trash mr-1"></i>
                    清空收藏
                  </el-button>
                </div>
              </div>

              <!-- 收藏统计 -->
              <div class="grid grid-cols-2 sm:grid-cols-4 gap-4">
                <div class="bg-gradient-to-r from-pink-50 to-rose-50 p-4 rounded-lg border border-pink-100">
                  <div class="text-2xl font-bold text-primary">{{ filteredFavorites.length }}</div>
                  <div class="text-sm text-gray-600">当前显示</div>
                </div>
                <div class="bg-gradient-to-r from-blue-50 to-indigo-50 p-4 rounded-lg border border-blue-100">
                  <div class="text-2xl font-bold text-blue-600">{{ favoriteBooks.length }}</div>
                  <div class="text-sm text-gray-600">总收藏</div>
                </div>
                <div class="bg-gradient-to-r from-green-50 to-emerald-50 p-4 rounded-lg border border-green-100">
                  <div class="text-2xl font-bold text-green-600">{{ favoriteBooks.filter(book => book.inStock).length }}</div>
                  <div class="text-sm text-gray-600">有库存</div>
                </div>
                <div class="bg-gradient-to-r from-orange-50 to-amber-50 p-4 rounded-lg border border-orange-100">
                  <div class="text-2xl font-bold text-orange-600">¥{{ totalFavoriteValue }}</div>
                  <div class="text-sm text-gray-600">总价值</div>
                </div>
              </div>

              <!-- 收藏图书列表 -->
              <div class="space-y-4">
                <div
                  v-for="book in filteredFavorites"
                  :key="book.id"
                  class="bg-white border border-gray-200 rounded-lg p-4 hover:shadow-md transition-all duration-300"
                >
                  <div class="flex flex-col sm:flex-row gap-4">
                    <!-- 图书封面 -->
                    <div class="flex-shrink-0">
                      <img
                        :src="book.cover"
                        :alt="book.title"
                        class="w-20 h-28 object-cover rounded-lg shadow-sm cursor-pointer hover:shadow-md transition-shadow"
                        @click="goToBookDetail(book.id)"
                      >
                    </div>

                    <!-- 图书信息 -->
                    <div class="flex-1 min-w-0">
                      <div class="flex flex-col sm:flex-row sm:items-start justify-between gap-2">
                        <div class="flex-1">
                          <h3
                            class="text-lg font-semibold text-gray-800 hover:text-primary cursor-pointer transition-colors line-clamp-1"
                            @click="goToBookDetail(book.id)"
                          >
                            {{ book.title }}
                          </h3>
                          <p class="text-gray-600 text-sm mb-1">作者：{{ book.author }}</p>
                          <p class="text-gray-500 text-sm mb-2">出版社：{{ book.publisher }}</p>
                          <p class="text-gray-600 text-sm line-clamp-2 mb-3">{{ book.description }}</p>

                          <!-- 标签和评分 -->
                          <div class="flex flex-wrap items-center gap-2 mb-3">
                            <el-tag size="small" type="info">{{ book.category }}</el-tag>
                            <div class="flex items-center">
                              <i class="fas fa-star text-yellow-400 mr-1"></i>
                              <span class="text-sm text-gray-600">{{ book.rating }}</span>
                            </div>
                            <el-tag v-if="!book.inStock" size="small" type="danger">缺货</el-tag>
                            <span class="text-xs text-gray-400">收藏于 {{ book.favoriteTime }}</span>
                          </div>
                        </div>

                        <!-- 价格和操作 -->
                        <div class="flex flex-col items-end gap-2">
                          <div class="text-right">
                            <div class="text-lg font-bold text-primary">¥{{ book.price }}</div>
                            <div class="text-sm text-gray-400 line-through">¥{{ book.originalPrice }}</div>
                          </div>

                          <div class="flex gap-2">
                            <el-button
                              v-if="book.inStock"
                              type="primary"
                              size="small"
                              @click="addToCart(book)"
                            >
                              <i class="fas fa-shopping-cart mr-1"></i>
                              加入购物车
                            </el-button>
                            <el-button
                              v-else
                              type="info"
                              size="small"
                              disabled
                            >
                              暂时缺货
                            </el-button>
                            <el-button
                              type="danger"
                              plain
                              size="small"
                              @click="removeFavorite(book.id)"
                            >
                              <i class="fas fa-heart-broken mr-1"></i>
                              取消收藏
                            </el-button>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- 空状态 -->
                <div v-if="filteredFavorites.length === 0" class="text-center py-12">
                  <div class="text-gray-400 mb-4">
                    <i class="fas fa-heart text-6xl"></i>
                  </div>
                  <h3 class="text-lg font-medium text-gray-600 mb-2">暂无收藏图书</h3>
                  <p class="text-gray-500 mb-4">去发现更多好书，添加到收藏夹吧！</p>
                  <el-button type="primary" @click="goToHome">
                    <i class="fas fa-search mr-2"></i>
                    去逛逛
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 底部页脚 -->
    <footer class="bg-gray-900 text-white py-10 mt-16">
      <div class="container mx-auto px-4">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-8">
          <!-- 关于我们 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">关于书香阁</h3>
            <p class="text-gray-400 text-sm">
              书香阁是专业的网上书店，提供超过10万种图书在线购买，支持快递配送和自提服务，让阅读触手可及。
            </p>
          </div>

          <!-- 快捷链接 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">快捷链接</h3>
            <ul class="space-y-2 text-sm">
              <li><router-link to="/category" class="text-gray-400 hover:text-primary">分类浏览</router-link></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">热门排行</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">最新上架</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">特价促销</a></li>
            </ul>
          </div>

          <!-- 客户服务 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">客户服务</h3>
            <ul class="space-y-2 text-sm">
              <li><a href="#" class="text-gray-400 hover:text-primary">常见问题</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">配送方式</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">支付方式</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">退换政策</a></li>
            </ul>
          </div>

          <!-- 联系方式 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">联系我们</h3>
            <ul class="space-y-3 text-sm">
              <li class="flex items-start">
                <i class="fas fa-map-marker-alt text-primary mt-1 mr-3"></i>
                <span class="text-gray-400">北京市朝阳区建国路88号</span>
              </li>
              <li class="flex items-center">
                <i class="fas fa-phone text-primary mr-3"></i>
                <span class="text-gray-400">400-800-1234</span>
              </li>
            </ul>
          </div>
        </div>

        <!-- 版权信息 -->
        <div class="border-t border-gray-800 mt-8 pt-8 text-center">
          <div class="text-gray-500 text-sm">
            © {{ new Date().getFullYear() }} 书香阁 版权所有
          </div>
        </div>
      </div>
    </footer>

    <!-- 回到顶部按钮 -->
    <BackToTop />



    <!-- 头像上传对话框 -->
    <el-dialog v-model="avatarDialogVisible" title="上传头像" width="500px" :before-close="handleAvatarDialogClose">
      <div class="avatar-upload-container">
        <div class="current-avatar mb-4 text-center">
          <h4 class="text-gray-700 mb-3">当前头像</h4>
          <el-avatar :size="80" :src="getImageUrl(userStore.userInfo?.avatar)">
            <i class="fas fa-user text-2xl"></i>
          </el-avatar>
        </div>

        <div class="upload-area">
          <el-upload
            ref="uploadRef"
            class="avatar-uploader"
            :action="uploadAction"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
            :on-error="handleAvatarError"
            :headers="uploadHeaders"
            accept="image/*"
            drag
          >
            <div class="upload-content">
              <i class="fas fa-cloud-upload-alt text-4xl text-gray-400 mb-3"></i>
              <div class="text-gray-600">
                <p class="mb-2">点击或拖拽图片到此处上传</p>
                <p class="text-sm text-gray-500">支持 JPG、PNG 格式，文件大小不超过 2MB</p>
              </div>
            </div>
          </el-upload>
        </div>

        <div v-if="previewAvatar" class="preview-area mt-4">
          <h4 class="text-gray-700 mb-3">预览</h4>
          <div class="flex justify-center">
            <el-avatar :size="80" :src="previewAvatar" />
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="avatarDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAvatarUpload" :disabled="!previewAvatar" :loading="avatarLoading">
            确定使用
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 地址管理对话框 -->
    <el-dialog
      v-model="addressDialogVisible"
      :title="addressDialogTitle"
      width="500px"
      :before-close="handleAddressDialogClose"
    >
      <el-form :model="addressForm" :rules="addressRules" ref="addressFormRef" label-width="80px">
        <el-form-item label="收货人" prop="name">
          <el-input
            v-model="addressForm.name"
            placeholder="请输入收货人姓名"
          />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="addressForm.phone"
            placeholder="请输入手机号"
            maxlength="11"
          />
        </el-form-item>

        <el-form-item label="省市区" prop="region">
          <el-cascader
            v-model="addressForm.region"
            :options="regionOptions"
            placeholder="请选择省市区"
            style="width: 100%"
            :props="{
              expandTrigger: 'hover',
              value: 'value',
              label: 'label',
              children: 'children',
              checkStrictly: false
            }"
            filterable
            clearable
          />
        </el-form-item>

        <el-form-item label="详细地址" prop="detail">
          <el-input
            v-model="addressForm.detail"
            type="textarea"
            :rows="3"
            placeholder="请输入详细地址（街道、门牌号等）"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="地址标签" prop="tag">
          <el-radio-group v-model="addressForm.tag">
            <el-radio label="home">家</el-radio>
            <el-radio label="company">公司</el-radio>
            <el-radio label="school">学校</el-radio>
            <el-radio label="other">其他</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-checkbox v-model="addressForm.isDefault">设为默认地址</el-checkbox>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addressDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddress" :loading="addressLoading">
            {{ isEditingAddress ? '保存修改' : '添加地址' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useCartStore } from '@/stores/cart'
import { ElMessage, ElMessageBox } from 'element-plus'
import { userAPI } from '@/api/user.js'
import BackToTop from '@/components/BackToTop.vue'
import { regionData } from 'element-china-area-data'

const router = useRouter()
const userStore = useUserStore()
const cartStore = useCartStore()

// 响应式数据
const searchKeyword = ref('')
const showMobileMenu = ref(false)
const activeTab = ref('basic')

// 计算购物车数量
const cartCount = computed(() => cartStore.cartCount)

// 计算筛选后的收藏图书
const filteredFavorites = computed(() => {
  let filtered = favoriteBooks.filter(book => {
    if (favoriteFilter.value === 'inStock') return book.inStock
    if (favoriteFilter.value === 'outOfStock') return !book.inStock
    return true
  })

  // 排序
  filtered.sort((a, b) => {
    switch (favoriteSortBy.value) {
      case 'time':
        return new Date(b.favoriteTime) - new Date(a.favoriteTime)
      case 'price':
        return parseFloat(a.price) - parseFloat(b.price)
      case 'rating':
        return b.rating - a.rating
      default:
        return 0
    }
  })

  return filtered
})

// 计算收藏图书总价值
const totalFavoriteValue = computed(() => {
  return favoriteBooks.reduce((total, book) => total + parseFloat(book.price), 0).toFixed(2)
})

// 左侧菜单项
const menuItems = reactive([
  { key: 'basic', label: '基本信息', icon: 'fas fa-user' },
  { key: 'avatar', label: '头像设置', icon: 'fas fa-image' },
  { key: 'security', label: '安全设置', icon: 'fas fa-shield-alt' },
  { key: 'address', label: '地址管理', icon: 'fas fa-map-marker-alt' },
  { key: 'favorites', label: '我的收藏', icon: 'fas fa-heart' }
])

// 个人资料表单
const profileForm = reactive({
  username: '',
  email: '',
  phone: '',
  gender: 0,
  birthday: null
})

// 地址列表
const addresses = reactive([])

// 收藏图书列表
const favoriteBooks = reactive([])

// 收藏筛选和排序
const favoriteFilter = ref('all') // all, inStock, outOfStock
const favoriteSortBy = ref('time') // time, price, rating

// 对话框控制
const avatarDialogVisible = ref(false)
const addressDialogVisible = ref(false)

// 表单引用
const passwordFormRef = ref(null)
const uploadRef = ref(null)
const addressFormRef = ref(null)

// 加载状态
const passwordLoading = ref(false)
const avatarLoading = ref(false)
const addressLoading = ref(false)

// 头像预览
const previewAvatar = ref('')
const selectedAvatarFile = ref(null)

// 地址管理状态
const isEditingAddress = ref(false)
const editingAddressId = ref(null)
const addressDialogTitle = computed(() => isEditingAddress.value ? '编辑地址' : '添加新地址')

// 修改密码表单
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})



// 地址表单
const addressForm = reactive({
  name: '',
  phone: '',
  region: [],
  detail: '',
  tag: 'home',
  isDefault: false
})

// 上传配置
const uploadAction = ref('https://jsonplaceholder.typicode.com/posts/') // 模拟上传接口
const uploadHeaders = reactive({
  'Authorization': 'Bearer token' // 实际项目中应该使用真实的token
})

// 地区选项数据（使用完整的中国省市区数据）
const regionOptions = reactive(regionData)

// 表单验证规则
const passwordRules = reactive({
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应为6-20位', trigger: 'blur' },
    {
      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{6,}$/,
      message: '密码应包含大小写字母和数字',
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})



const addressRules = reactive({
  name: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度应为2-10个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  region: [
    { required: true, message: '请选择省市区', trigger: 'change' }
  ],
  detail: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 5, max: 100, message: '详细地址长度应为5-100个字符', trigger: 'blur' }
  ],
  tag: [
    { required: true, message: '请选择地址标签', trigger: 'change' }
  ]
})

// 方法
const toggleMobileMenu = () => {
  showMobileMenu.value = !showMobileMenu.value
}

const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    ElMessage.info(`搜索功能开发中，搜索关键词：${searchKeyword.value}`)
  }
}

const goToCart = () => {
  router.push('/cart')
}

// 处理下拉菜单命令
const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      // 已经在个人资料页面，不需要跳转
      break
    case 'orders':
      router.push('/orders')
      break
    case 'settings':
      router.push('/settings')
      break
    case 'logout':
      handleLogout()
      break
  }
}

// 处理登出
const handleLogout = () => {
  userStore.logout()
  router.push('/login')
}

// 保存个人资料
const saveProfile = async () => {
  try {
    // 准备提交的数据
    const profileData = {
      username: profileForm.username,
      email: profileForm.email,
      phone: profileForm.phone,
      gender: profileForm.gender,
      birthDate: profileForm.birthday ? formatDateForSubmit(profileForm.birthday) : null
    }

    // 调用API保存个人资料
    const response = await userAPI.updateUserProfile(profileData)
    if (response.code === 200) {
      ElMessage.success('个人资料保存成功')
      // 更新用户store中的信息
      await loadUserProfile()
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error) {
    console.error('保存个人资料失败：', error)
    ElMessage.error((error.response?.data?.message || error.message))
  }
}

// 格式化日期用于提交
const formatDateForSubmit = (date) => {
  if (!date) return null
  const d = new Date(date)
  return d.getFullYear() + '-' +
         String(d.getMonth() + 1).padStart(2, '0') + '-' +
         String(d.getDate()).padStart(2, '0')
}

// 获取图片URL
const getImageUrl = (url) => {
  if (!url) return ''

  // 如果是完整的URL，直接返回
  if (url.startsWith('http')) {
    return url
  }

  // 如果是上传的文件路径
  if (url.startsWith('/uploads/')) {
    return `http://localhost:8081/api${url}`
  }

  // 如果是静态资源路径
  if (url.startsWith('/assets/')) {
    return `http://localhost:8081/api${url}`
  }

  // 其他情况，添加API前缀
  return `/api${url}`
}

// 重置个人资料
const resetProfile = () => {
  // 重置为用户信息
  profileForm.username = userStore.userInfo?.username || ''
  profileForm.email = userStore.userInfo?.email || ''
  profileForm.phone = userStore.userInfo?.phone || ''
  profileForm.gender = userStore.userInfo?.gender || 0
  profileForm.birthday = userStore.userInfo?.birthday || null
}

// 上传头像
const uploadAvatar = () => {
  avatarDialogVisible.value = true
  previewAvatar.value = ''
}

// 重置密码表单
const resetPasswordForm = () => {
  passwordForm.currentPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordFormRef.value?.resetFields()
}



const handleAvatarDialogClose = () => {
  previewAvatar.value = ''
  selectedAvatarFile.value = null
  avatarDialogVisible.value = false
}

// 提交密码修改
const submitPasswordChange = async () => {
  if (!passwordFormRef.value) return

  try {
    await passwordFormRef.value.validate()
    passwordLoading.value = true

    // 调用API修改密码
    const passwordData = {
      currentPassword: passwordForm.currentPassword,
      newPassword: passwordForm.newPassword
    }

    const response = await userAPI.changeUserPassword(passwordData)

    if (response.code === 200) {
      ElMessage.success('密码修改成功，请重新登录')
      resetPasswordForm()

      // 密码修改成功后，自动登出
      setTimeout(() => {
        handleLogout()
      }, 1000)
    } else {
      ElMessage.error(response.message || '密码修改失败')
    }

  } catch (error) {
    if (error !== false) { // 表单验证失败时error为false
      console.error('密码修改失败：', error)
      ElMessage.error((error.response?.data?.message || error.message || '请检查当前密码是否正确'))
    }
  } finally {
    passwordLoading.value = false
  }
}



// 加载地址列表
const loadAddressList = async () => {
  try {
    const response = await userAPI.getUserAddressList()
    if (response.data && Array.isArray(response.data)) {
      addresses.splice(0, addresses.length, ...response.data)
    }
  } catch (error) {
    console.error('加载地址列表失败：', error)
    ElMessage.error('加载地址列表失败')
  }
}

// 添加地址
const addAddress = () => {
  isEditingAddress.value = false
  editingAddressId.value = null
  resetAddressForm()
  addressDialogVisible.value = true
}

// 编辑地址
const editAddress = (address) => {
  isEditingAddress.value = true
  editingAddressId.value = address.id

  // 填充表单数据
  addressForm.name = address.name
  addressForm.phone = address.phone
  addressForm.detail = address.detail || address.fullAddress.split(' ').slice(-1)[0]
  addressForm.tag = address.tag || 'home'
  addressForm.isDefault = address.isDefault

  // 根据省市区数据构建region数组
  if (address.province && address.city && address.district) {
    // 使用智能匹配来查找对应的地区代码
    addressForm.region = smartMatchRegion(address.province, address.city, address.district)
  } else if (address.province && address.city) {
    // 只有省市数据
    addressForm.region = smartMatchRegion(address.province, address.city, null)
  } else if (address.province) {
    // 只有省份数据
    addressForm.region = smartMatchRegion(address.province, null, null)
  } else {
    // 没有详细的省市区数据，使用默认值
    addressForm.region = []
  }

  addressDialogVisible.value = true
}

// 重置地址表单
const resetAddressForm = () => {
  addressForm.name = ''
  addressForm.phone = ''
  addressForm.region = []
  addressForm.detail = ''
  addressForm.tag = 'home'
  addressForm.isDefault = false
}

// 地址对话框关闭处理
const handleAddressDialogClose = () => {
  addressFormRef.value?.resetFields()
  addressDialogVisible.value = false
  isEditingAddress.value = false
  editingAddressId.value = null
}

// 提交地址
const submitAddress = async () => {
  if (!addressFormRef.value) return

  try {
    await addressFormRef.value.validate()
    addressLoading.value = true

    // 获取地区详细信息
    const regionDetails = getRegionDetails(addressForm.region)
    const fullAddress = `${regionDetails.provinceName} ${regionDetails.cityName} ${regionDetails.districtName} ${addressForm.detail}`.trim()

    // 构建地址数据
    const addressData = {
      name: addressForm.name,
      phone: addressForm.phone,
      province: regionDetails.provinceName,
      city: regionDetails.cityName,
      district: regionDetails.districtName,
      detail: addressForm.detail,
      fullAddress: fullAddress,
      tag: addressForm.tag,
      isDefault: addressForm.isDefault
    }

    if (isEditingAddress.value) {
      // 编辑地址
      await userAPI.updateUserAddress(editingAddressId.value, addressData)
      ElMessage.success('地址修改成功')
    } else {
      // 添加新地址
      await userAPI.addUserAddress(addressData)
      ElMessage.success('地址添加成功')
    }

    // 重新加载地址列表
    await loadAddressList()
    addressDialogVisible.value = false

  } catch (error) {
    if (error !== false) {
      console.error('地址操作失败：', error)
      ElMessage.error(error.response?.data?.message || error.message || '操作失败，请重试')
    }
  } finally {
    addressLoading.value = false
  }
}

// 获取地区标签
const getRegionLabels = (regionValues) => {
  const labels = []
  let currentOptions = regionOptions

  for (const value of regionValues) {
    const option = currentOptions.find(opt => opt.value === value)
    if (option) {
      labels.push(option.label)
      currentOptions = option.children || []
    }
  }

  return labels
}

// 获取地区详细信息（包含省市区的完整信息）
const getRegionDetails = (regionValues) => {
  const details = {
    province: '',
    city: '',
    district: '',
    provinceName: '',
    cityName: '',
    districtName: ''
  }

  if (regionValues && regionValues.length > 0) {
    const labels = getRegionLabels(regionValues)

    if (labels.length >= 1) {
      details.province = regionValues[0]
      details.provinceName = labels[0]
    }
    if (labels.length >= 2) {
      details.city = regionValues[1]
      details.cityName = labels[1]
    }
    if (labels.length >= 3) {
      details.district = regionValues[2]
      details.districtName = labels[2]
    }
  }

  return details
}

// 根据标签查找地区值（用于编辑地址时回填数据）
const findRegionValue = (label, options) => {
  for (const option of options) {
    if (option.label === label) {
      return option.value
    }
    if (option.children) {
      const childValue = findRegionValue(label, option.children)
      if (childValue) return childValue
    }
  }
  return null
}

// 根据地区值查找标签（用于显示）
const findRegionLabel = (value, options) => {
  for (const option of options) {
    if (option.value === value) {
      return option.label
    }
    if (option.children) {
      const childLabel = findRegionLabel(value, option.children)
      if (childLabel) return childLabel
    }
  }
  return null
}

// 智能匹配地区（支持模糊匹配）
const smartMatchRegion = (provinceName, cityName, districtName) => {
  const result = []

  // 查找省份
  const province = regionOptions.find(p =>
    p.label.includes(provinceName) || provinceName.includes(p.label.replace(/省|市|自治区|特别行政区/g, ''))
  )

  if (province) {
    result.push(province.value)

    if (cityName && province.children) {
      // 查找城市
      const city = province.children.find(c =>
        c.label.includes(cityName) || cityName.includes(c.label.replace(/市|区|县|自治州|地区|盟/g, ''))
      )

      if (city) {
        result.push(city.value)

        if (districtName && city.children) {
          // 查找区县
          const district = city.children.find(d =>
            d.label.includes(districtName) || districtName.includes(d.label.replace(/区|县|市|镇|乡|街道/g, ''))
          )

          if (district) {
            result.push(district.value)
          }
        }
      }
    }
  }

  return result
}

// 获取地址标签显示文本
const getTagLabel = (tag) => {
  const tagMap = {
    home: '家',
    company: '公司',
    school: '学校',
    other: '其他'
  }
  return tagMap[tag] || '其他'
}

// 获取地址标签类型
const getTagType = (tag) => {
  const typeMap = {
    home: 'success',
    company: 'warning',
    school: 'info',
    other: ''
  }
  return typeMap[tag] || ''
}

// 删除地址
const deleteAddress = (addressId) => {
  ElMessageBox.confirm('确定要删除这个地址吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await userAPI.deleteUserAddress(addressId)
      ElMessage.success('地址删除成功')
      // 重新加载地址列表
      await loadAddressList()
    } catch (error) {
      console.error('删除地址失败：', error)
      ElMessage.error(error.response?.data?.message || error.message || '删除地址失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 格式化收藏时间
const formatFavoriteTime = (dateString) => {
  if (!dateString) return new Date().toISOString().split('T')[0]

  try {
    const date = new Date(dateString)
    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      return new Date().toISOString().split('T')[0]
    }

    // 格式化为 YYYY-MM-DD
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')

    return `${year}-${month}-${day}`
  } catch (error) {
    console.error('时间格式化失败:', error)
    return new Date().toISOString().split('T')[0]
  }
}

// 加载收藏列表
const loadFavoriteBooks = async () => {
  try {
    const response = await userAPI.getUserFavorites()
    if (response && response.code === 200) {
      // 清空现有数据
      favoriteBooks.splice(0)

      // 处理返回的数据
      const favorites = response.data.map(item => ({
        id: item.book_id,
        title: item.title,
        author: item.author,
        publisher: item.publisher,
        price: item.price ? item.price.toString() : '0.00',
        originalPrice: item.original_price ? item.original_price.toString() : null,
        cover: getImageUrl(item.cover) || 'https://design.gemcoder.com/staticResource/echoAiSystemImages/f94fa5368ec54a9a1fafd8c376d0aa53.png',
        description: item.description || '暂无简介',
        rating: item.rating || 4.5,
        favoriteTime: item.created_at ? formatFavoriteTime(item.created_at) : formatFavoriteTime(new Date()),
        category: '图书',
        inStock: item.stock > 0
      }))

      // 添加到响应式数组
      favoriteBooks.push(...favorites)
    } else {
      ElMessage.error(response?.message || '获取收藏列表失败')
    }
  } catch (error) {
    console.error('加载收藏列表失败:', error)
    ElMessage.error('加载收藏列表失败，请稍后重试')
  }
}

// 收藏相关方法
const removeFavorite = async (bookId) => {
  ElMessageBox.confirm('确定要取消收藏这本书吗？', '取消收藏', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await userAPI.removeFavorite(bookId)
      if (response && response.code === 200) {
        const index = favoriteBooks.findIndex(book => book.id === bookId)
        if (index > -1) {
          favoriteBooks.splice(index, 1)
        }
        ElMessage.success('已取消收藏')
      } else {
        ElMessage.error(response?.message || '取消收藏失败')
      }
    } catch (error) {
      console.error('取消收藏失败:', error)
      ElMessage.error('取消收藏失败，请稍后重试')
    }
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}

const clearAllFavorites = () => {
  if (favoriteBooks.length === 0) {
    ElMessage.warning('收藏夹已经是空的')
    return
  }

  ElMessageBox.confirm('确定要清空所有收藏吗？此操作不可恢复。', '清空收藏', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await userAPI.clearFavorites()
      if (response && response.code === 200) {
        favoriteBooks.splice(0)
        ElMessage.success('收藏夹已清空')
      } else {
        ElMessage.error(response?.message || '清空收藏失败')
      }
    } catch (error) {
      console.error('清空收藏失败:', error)
      ElMessage.error('清空收藏失败，请稍后重试')
    }
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}

const addToCart = async (book) => {
  if (!book.inStock) {
    ElMessage.warning('该商品暂时缺货')
    return
  }
  try {
    await cartStore.addToCart(book)
    // 消息提示已在store中处理，这里不需要重复提示
  } catch (error) {
    console.error('添加到购物车失败:', error)
  }
}

const goToBookDetail = (bookId) => {
  router.push(`/book/${bookId}`)
}

const goToHome = () => {
  router.push('/home')
}

// 头像上传相关方法
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }

  // 保存选中的文件
  selectedAvatarFile.value = file

  // 创建预览
  const reader = new FileReader()
  reader.onload = (e) => {
    previewAvatar.value = e.target.result
  }
  reader.readAsDataURL(file)

  return false // 阻止自动上传，手动控制
}

const handleAvatarSuccess = (response, file) => {
  // 这里处理上传成功的响应
  ElMessage.success('头像上传成功')
  previewAvatar.value = URL.createObjectURL(file.raw)
}

const handleAvatarError = (error) => {
  ElMessage.error('头像上传失败，请重试')
  console.error('Upload error:', error)
}

const confirmAvatarUpload = async () => {
  if (!selectedAvatarFile.value) {
    ElMessage.warning('请先选择头像')
    return
  }

  try {
    avatarLoading.value = true

    // 创建FormData对象
    const formData = new FormData()
    formData.append('file', selectedAvatarFile.value)

    // 调用API上传头像
    const response = await userAPI.uploadUserAvatar(formData)

    if (response.code === 200) {
      ElMessage.success('头像上传成功')
      // 重新加载用户资料以获取最新信息
      await loadUserProfile()
      // 关闭对话框并重置状态
      avatarDialogVisible.value = false
      previewAvatar.value = ''
      selectedAvatarFile.value = null
    } else {
      ElMessage.error(response.message || '头像上传失败')
    }

  } catch (error) {
    console.error('头像上传失败：', error)
    ElMessage.error('头像上传失败：' + (error.response?.data?.message || error.message))
  } finally {
    avatarLoading.value = false
  }
}

// 加载用户个人资料
const loadUserProfile = async () => {
  try {
    const response = await userAPI.getUserProfile()
    if (response.code === 200) {
      const profile = response.data
      // 更新表单数据
      Object.assign(profileForm, {
        username: profile.username || '',
        email: profile.email || '',
        phone: profile.phone || '',
        gender: profile.gender || 0,
        birthday: profile.birthDate ? new Date(profile.birthDate) : null
      })

      // 更新用户store
      userStore.updateUserInfo({
        ...userStore.userInfo,
        username: profile.username,
        email: profile.email,
        phone: profile.phone,
        realName: profile.realName,
        avatar: profile.avatar,
        gender: profile.gender,
        birthDate: profile.birthDate
      })
    }
  } catch (error) {
    console.error('加载用户资料失败：', error)
    ElMessage.error('加载个人资料失败')
  }
}

// 初始化数据
const initData = () => {
  // 初始化个人资料表单
  profileForm.username = userStore.userInfo?.username || ''
  profileForm.email = userStore.userInfo?.email || ''
  profileForm.phone = userStore.userInfo?.phone || ''
  profileForm.gender = userStore.userInfo?.gender || ''
  profileForm.birthday = userStore.userInfo?.birthday || null
}

// 生命周期
onMounted(async () => {
  initData()
  // 加载最新的用户资料
  await loadUserProfile()
  // 加载地址列表
  await loadAddressList()
  // 加载收藏列表
  await loadFavoriteBooks()
})
</script>

<style scoped>
/* 自定义样式 */
:root {
  --primary: #FF6B8A;
  --primary-light: #FFB3C6;
  --primary-dark: #E55A7A;
  --secondary: #FFF0F3;
  --accent: #FF8FA3;
  --success: #4CAF50;
  --warning: #FF9800;
  --info: #2196F3;
  --dark: #2D3748;
  --gray: #718096;
  --light-gray: #F7FAFC;
  --white: #FFFFFF;
}

/* 确保主题色在整个组件中生效 */
.profile-container {
  --el-color-primary: #FF6B8A;
  --el-color-primary-light-3: #FFB3C6;
  --el-color-primary-dark-2: #E55A7A;
}

.el-dropdown-link {
  display: flex;
  align-items: center;
  color: #606266;
  transition: color 0.3s ease;
}

.el-dropdown-link:hover {
  color: var(--primary);
}

/* 搜索框样式 */
.search-input :deep(.el-input__wrapper) {
  border-radius: 9999px;
  border: 1px solid #d1d5db;
  transition: all 0.3s ease;
}

.search-input :deep(.el-input__wrapper):hover {
  border-color: var(--primary);
}

.search-input :deep(.el-input__wrapper.is-focus) {
  border-color: var(--primary);
  box-shadow: 0 0 0 2px rgba(255, 107, 139, 0.2);
}

/* 搜索按钮样式 */
.search-button {
  background-color: #FF6B8B !important;
}

.search-button:hover {
  background-color: rgba(255, 107, 139, 0.8) !important;
}

/* 主题色定义 */
.text-primary {
  color: rgb(255, 107, 139) !important;
}

.bg-primary {
  background-color: #FF6B8B !important;
}

.border-primary {
  border-color: #FF6B8B !important;
}

.bg-primary\/10 {
  background-color: rgba(255, 107, 139, 0.1) !important;
}

.hover\:text-primary:hover {
  color: #FF6B8B !important;
}

.cart-badge {
  z-index: 10;
  transform: translate(25%, -25%);
  min-width: 18px;
  height: 18px;
}

/* 表单样式 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #374151;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper):hover {
  border-color: var(--primary);
}

:deep(.el-input__wrapper.is-focus) {
  border-color: var(--primary);
  box-shadow: 0 0 0 2px rgba(255, 107, 139, 0.1);
}

:deep(.el-button--primary) {
  background-color: var(--primary) !important;
  border-color: var(--primary) !important;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
  color: white !important;
}

:deep(.el-button--primary:hover) {
  background-color: var(--primary-dark) !important;
  border-color: var(--primary-dark) !important;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 107, 139, 0.3);
  color: white !important;
}

:deep(.el-button--primary:focus) {
  background-color: var(--primary) !important;
  border-color: var(--primary) !important;
  color: white !important;
}

:deep(.el-button--primary:active) {
  background-color: var(--primary-dark) !important;
  border-color: var(--primary-dark) !important;
  color: white !important;
}

:deep(.el-radio__input.is-checked .el-radio__inner) {
  background-color: var(--primary) !important;
  border-color: var(--primary) !important;
}

:deep(.el-radio__input.is-checked + .el-radio__label) {
  color: var(--primary) !important;
}

/* 强制覆盖单选按钮样式 */
.profile-container :deep(.el-radio__input.is-checked .el-radio__inner) {
  background-color: #FF6B8A !important;
  border-color: #FF6B8A !important;
}

.profile-container :deep(.el-radio__input.is-checked + .el-radio__label) {
  color: #FF6B8A !important;
  font-weight: 500;
}

.profile-container :deep(.el-radio__inner:hover) {
  border-color: #FF6B8A !important;
}

.profile-container :deep(.el-radio:hover .el-radio__inner) {
  border-color: #FF6B8A !important;
}

.profile-container :deep(.el-radio__input:focus .el-radio__inner) {
  border-color: #FF6B8A !important;
  box-shadow: 0 0 0 2px rgba(255, 107, 139, 0.2) !important;
}

:deep(.el-date-editor.el-input) {
  width: 100%;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .container {
    padding-left: 1rem;
    padding-right: 1rem;
  }

  .grid-cols-1.lg\\:grid-cols-3 {
    grid-template-columns: 1fr;
  }
}

/* 卡片悬停效果 */
.card-hover {
  transition: all 0.3s ease;
}

.card-hover:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -5px rgba(0, 0, 0, 0.04);
}

/* 文本截断 */
.line-clamp-1 {
  display: -webkit-box;
  -webkit-line-clamp: 1;
  line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 收藏页面特殊样式 */
.favorite-book-card {
  transition: all 0.3s ease;
}

.favorite-book-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.favorite-book-card img {
  transition: all 0.3s ease;
}

.favorite-book-card:hover img {
  transform: scale(1.05);
}

/* 统计卡片样式 */
.stats-card {
  background: linear-gradient(135deg, rgba(255, 107, 139, 0.1) 0%, rgba(255, 107, 139, 0.05) 100%);
  border: 1px solid rgba(255, 107, 139, 0.2);
  transition: all 0.3s ease;
}

.stats-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(255, 107, 139, 0.2);
}

/* 选择器样式 */
:deep(.el-select .el-input__wrapper) {
  border-radius: 8px;
}

:deep(.el-select .el-input__wrapper):hover {
  border-color: var(--primary);
}

:deep(.el-select .el-input__wrapper.is-focus) {
  border-color: var(--primary);
  box-shadow: 0 0 0 2px rgba(255, 107, 139, 0.1);
}

/* 对话框样式 */
:deep(.el-dialog__header) {
  padding: 20px 20px 10px;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  padding: 10px 20px 20px;
  border-top: 1px solid #f0f0f0;
}

/* 头像上传样式 */
.avatar-upload-container {
  text-align: center;
}

.avatar-uploader :deep(.el-upload) {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
  width: 100%;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: var(--primary);
  background-color: rgba(255, 107, 139, 0.05);
}

.upload-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 20px;
}

.preview-area {
  text-align: center;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

/* 表单样式增强 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #374151;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper):hover {
  border-color: var(--primary);
}

:deep(.el-input__wrapper.is-focus) {
  border-color: var(--primary);
  box-shadow: 0 0 0 2px rgba(255, 107, 139, 0.1);
}

/* 验证码输入框样式 */
.flex {
  display: flex;
}

.gap-2 {
  gap: 8px;
}

.flex-1 {
  flex: 1;
}

/* 地址管理样式 */
.address-card {
  transition: all 0.3s ease;
  border: 1px solid #e5e7eb;
}

.address-card:hover {
  border-color: var(--primary);
  box-shadow: 0 4px 12px rgba(255, 107, 139, 0.1);
}

/* 级联选择器样式 */
:deep(.el-cascader) {
  width: 100%;
}

:deep(.el-cascader .el-input__wrapper) {
  border-radius: 8px;
}

:deep(.el-cascader .el-input__wrapper):hover {
  border-color: var(--primary);
}

:deep(.el-cascader .el-input__wrapper.is-focus) {
  border-color: var(--primary);
  box-shadow: 0 0 0 2px rgba(255, 107, 139, 0.1);
}

/* 文本域样式 */
:deep(.el-textarea__inner) {
  border-radius: 8px;
  transition: all 0.3s ease;
}

:deep(.el-textarea__inner):hover {
  border-color: var(--primary);
}

:deep(.el-textarea__inner):focus {
  border-color: var(--primary);
  box-shadow: 0 0 0 2px rgba(255, 107, 139, 0.1);
}

/* 标签样式 */
.address-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 40px 20px;
}

.empty-state i {
  color: #d1d5db;
  margin-bottom: 16px;
}

.empty-state h3 {
  color: #6b7280;
  margin-bottom: 8px;
}

.empty-state p {
  color: #9ca3af;
  margin-bottom: 16px;
}

/* 强制覆盖Element Plus按钮样式 */
.profile-container :deep(.el-button.el-button--primary) {
  background-color: #FF6B8A !important;
  border-color: #FF6B8A !important;
  color: #ffffff !important;
}

.profile-container :deep(.el-button.el-button--primary:hover) {
  background-color: #E55A7A !important;
  border-color: #E55A7A !important;
  color: #ffffff !important;
}

.profile-container :deep(.el-button.el-button--primary:focus) {
  background-color: #FF6B8A !important;
  border-color: #FF6B8A !important;
  color: #ffffff !important;
}

.profile-container :deep(.el-button.el-button--primary:active) {
  background-color: #E55A7A !important;
  border-color: #E55A7A !important;
  color: #ffffff !important;
}

/* 确保表单中的按钮样式 */
.profile-container :deep(.el-form .el-button--primary) {
  background-color: #FF6B8A !important;
  border-color: #FF6B8A !important;
  color: #ffffff !important;
  font-weight: 500;
  border-radius: 8px;
  padding: 8px 16px;
  transition: all 0.3s ease;
}

.profile-container :deep(.el-form .el-button--primary:hover) {
  background-color: #E55A7A !important;
  border-color: #E55A7A !important;
  color: #ffffff !important;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 107, 139, 0.3);
}
</style>
